package com.os.sys.common.configuration;


import com.os.sys.common.utility.StringClass;
import com.os.sys.common.utility.XJsonInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * Created by Administrator on 2016/12/13.
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {
    private static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * bean校验未通过异常
     *
     * @see org.springframework.validation.Validator
     * @see org.springframework.validation.DataBinder
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    private XJsonInfo illegalParamsExceptionHandler(Exception ex) {
//        if (ex instanceof MissingServletRequestParameterException) {
//            return new XJsonInfo(false, "接口不存在");
//        }

        StackTraceElement stackTraceElement = ex.getStackTrace()[ex.getStackTrace().length - 1];
        StringBuilder sb = new StringBuilder();
        sb.append(getDetailErrorMsg(ex));
//        sb.append("  File=" + stackTraceElement.getFileName());
//        sb.append("  Line=" + stackTraceElement.getLineNumber());
//        sb.append("  Method=" + stackTraceElement.getMethodName());

        LOGGER.error("error--------->" + sb.toString(), ex);
        return new XJsonInfo(false, sb.toString());
    }

    private String getDetailErrorMsg(Exception ex) {
        String msg = "";
        try {
            msg = ex.getCause().getCause().getMessage();
        } catch (Exception er) {
            msg = StringClass.isNullOrEmpty(ex.getMessage()) ? ex.toString() : ex.getMessage();
        }
        return msg;
    }
}
